from flask import Flask, request, jsonify, send_from_directory, render_template, redirect, url_for
import os
import startcode
import sys
import pose_recognition as pr
import base64
import io
import cv2
import numpy as np
from PIL import Image
from matplotlib.animation import FuncAnimation
from flask_cors import CORS
from threading import Thread
# from celery import Celery
# from Celery_app import make_celery, celery

video_path = ""
side = 0
height_real = 0

app = Flask(__name__)
CORS(app)

# app.config.update(
#     CELERY_BROKER_URL='redis://localhost:6379/0',
#     CELERY_RESULT_BACKEND='redis://localhost:6379/0'
# )
# celery.conf.update(app.config)


# 创建一个文件夹invideo，用来存放用户上传的视频
app.config['INVIDEO_FOLDER'] = 'invideo'
if not os.path.exists(app.config['INVIDEO_FOLDER']):
    os.makedirs(app.config['INVIDEO_FOLDER'])

# 访问根目录时，调用index()函数
@app.route('/')
def index():
    return render_template('index.html')



# @app.route('/data', methods=['GET'])
# def data():
#     # 这里需要实现从后端获取数据的逻辑
#     # 例如，从全局变量或数据库中获取数据
#     data = {
#         'attacks_count':     pr.attacks_count,  # 示例数据
#         'sum_distance':      pr.global_sum_distance,
#         'right_hand_angle':  pr.global_right_hand_angle,
#         'right_ankle_angle': pr.global_right_ankle_angle,
#         'left_ankle_angle':  pr.global_left_ankle_angle,
#         'right_knee_angle':  pr.global_right_knee_angle,
#         'left_knee_angle':   pr.global_left_knee_angle,
#         'right_shoulder':    pr.global_right_shoulder,
#         'left_shoulder':     pr.global_left_shoulder,
#         'right_hip':         pr.global_right_hip,
#         'left_hip':          pr.global_left_hip
#     }
#     return jsonify(data)


# @app.route('/invideo', methods=['POST'])
# def upload_video():
#     global video_path
#     global side
#     global height_real
#     # 如果video为空
#     if 'video' not in request.files:
#         return jsonify({'error': '没有视频被上传'}), 400
    
#     # 获取网页上传的视频
#     video = request.files['video']
    
#     # 获取网页上传的side
#     side = request.form.get('side', type=int)
#     # print(type(side))
#     # 获取网页上传的真实身高
#     height_real = request.form.get('height', type=int)
#     # print(type(height_real))


#     if not video:
#         return jsonify({'error': '没有视频被上传'}), 400

#     if video.filename == '':
#         return jsonify({'error': '没有选择视频文件'}), 400
    
#     print("视频文件有效，准备保存")

#     if video:
#         # 将服务器invideo文件夹与视频文件名组合   **invideo/video.filename   invideo/视频文件名
#         video_path = os.path.join(app.config['INVIDEO_FOLDER'], video.filename)
#         # print(type(video_path))
#         video.save(video_path)
        
#         print("视频已保存，准备调用 startcode函数")

#         # 调用startcode，执行后端算法
#         data = startcode.startcode(video_path, side, height_real)
#         print("完成程序")

#         return jsonify(data)
    
# @app.route('/competition', methods=['POST'])
# def competition11():
#     video = request.files.get('video')
#     height = request.form.get('height', type=int)
#     side = request.form.get('side')

#     if not video:
#         return jsonify({'error': 'No video file uploaded'}), 400

#     video_path = os.path.join(app.config['INVIDEO_FOLDER'], video.filename)
#     video.save(video_path)

#     # 调用 startcode.py
#     startcode.startcode(video_path, side, height)
#     return jsonify({'message': 'Competition analysis started'})

    # global video_path
    # global side
    # global height_real
    # # 如果video为空
    # if 'video' not in request.files:
    #     return jsonify({'error': '没有视频被上传'}), 400
    
    # # 获取网页上传的视频
    # video = request.files['video']
    
    # # 获取网页上传的side
    # side = request.form.get('side', type=int)
    # # print(type(side))
    # # 获取网页上传的真实身高
    # height_real = request.form.get('height', type=int)
    # # print(type(height_real))


    # if not video:
    #     return jsonify({'error': '没有视频被上传'}), 400

    # if video.filename == '':
    #     return jsonify({'error': '没有选择视频文件'}), 400
    
    # print("视频文件有效，准备保存")

    # if video:
    #     # 将服务器invideo文件夹与视频文件名组合   **invideo/video.filename   invideo/视频文件名
    #     video_path = os.path.join(app.config['INVIDEO_FOLDER'], video.filename)
    #     # print(type(video_path))
    #     video.save(video_path)
        
    #     print("视频已保存，准备调用 startcode函数")

    #     # 调用startcode，执行后端算法
    #     data = startcode.startcode(video_path, side, height_real)
    #     print("完成程序")

    #     return jsonify(data)







# @app.route('/analysis', methods=['POST'])
# def analysis11():
#     video = request.files.get('video')
#     height = request.form.get('height', type=int)
#     side = request.form.get('side')

#     if not video:
#         return jsonify({'error': 'No video file uploaded'}), 400

#     video_path = os.path.join(app.config['INVIDEO_FOLDER'], video.filename)
#     video.save(video_path)

#     # 调用 startcode.py
#     startcode.startcode(video_path, side, height)
#     return jsonify({'message': 'Action analysis started'})

# @app.route('/competition')
# def competition():
#     global video_path
#     global side
#     global height_real
#     # 如果video为空
#     if 'video' not in request.files:
#         return jsonify({'error': '没有视频被上传'}), 400
    
#     # 获取网页上传的视频
#     video = request.files['video']
    
#     # 获取网页上传的side
#     side = request.form.get('side', type=int)
#     # print(type(side))
#     # 获取网页上传的真实身高
#     height_real = request.form.get('height', type=int)
#     # print(type(height_real))


#     if not video:
#         return jsonify({'error': '没有视频被上传'}), 400

#     if video.filename == '':
#         return jsonify({'error': '没有选择视频文件'}), 400
    
#     print("视频文件有效，准备保存")
#     return render_template('competition.html')



# @app.route('/analysis')
# def analysis():
#     global video_path
#     global side
#     global height_real
#     # 如果video为空
#     if 'video' not in request.files:
#         return jsonify({'error': '没有视频被上传'}), 400
    
#     # 获取网页上传的视频
#     video = request.files['video']
    
#     # 获取网页上传的side
#     side = request.form.get('side', type=int)
#     # print(type(side))
#     # 获取网页上传的真实身高
#     height_real = request.form.get('height', type=int)
#     # print(type(height_real))


#     if not video:
#         return jsonify({'error': '没有视频被上传'}), 400

#     if video.filename == '':
#         return jsonify({'error': '没有选择视频文件'}), 400
    
#     print("视频文件有效，准备保存")


#     return render_template('analysis.html')


@app.route('/upload', methods=['POST'])
def upload_video():
    video = request.files.get('video')
    side = request.form.get('side', type=int)
    height = request.form.get('height', type=int)
    button_type = request.form.get('button_type')
    if not video:
        return jsonify({'error': 'No video file uploaded'}), 400

    video_path = os.path.join(app.config['INVIDEO_FOLDER'], video.filename)
    video.save(video_path)
    return jsonify({
        'video_path': video_path,
        'side': side,
        'height': height,
        'button_type': button_type
    })

    # 根据按钮类型决定跳转页面和调用函数
    # button_type = request.form.get('button_type')
    # if button_type == 'competition':
    #     startcode.startcode(video_path, side, height)
    #     return redirect(url_for('competition'))
    # elif button_type == 'analysis':
    #     startcode.startcode_two(video_path, side, height)
    #     return redirect(url_for('analysis'))

@app.route('/competition')
def competition():
    video_path = request.args.get('video_path')
    side = int(request.args.get('side'))
    height = int(request.args.get('height'))
    
    # 在后台线程中运行 startcode 函数
    # thread = Thread(target=startcode.startcode, args=(video_path, side, height)).start()
    thread = Thread(target=startcode.startcode, args=(video_path, side, height))
    thread.start()
    # thread.join()  # 等待线程结束
    # startcode.startcode.delay(video_path, side, height)
    return render_template('competition.html')

@app.route('/analysis')
def analysis():
    video_path = request.args.get('video_path')
    side = int(request.args.get('side'))
    height = int(request.args.get('height'))
    
    # 在后台线程中运行 startcode_two 函数
    # thread = Thread(target=startcode.startcode_two, args=(video_path, side, height)).start()
    thread = Thread(target=startcode.startcode_two, args=(video_path, side, height))
    thread.start()
    # thread.join()  # 等待线程结束
    # startcode.startcode_two.delay(video_path, side, height)
    return render_template('analysis.html')


if __name__ == '__main__':
    host_address = '127.0.0.1'  # 监听本地请求
    # 使用4090端口
    host_port = 5000
    print(f"访问本地服务器地址: http://{host_address}:{host_port}")
    # 运行app应用
    app.run(debug=True, host=host_address, port=host_port)
